package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.SpecParam;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.search.clients.CategoryClient;
import com.leyou.search.clients.GoodsClient;
import com.leyou.search.clients.SpecificationClient;
import com.leyou.search.pojo.Goods;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class IndexService {

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecificationClient specificationClient;


    /**
     * 把数据库的数据保存到索引库
     *
     * @param spuBo
     * @return
     */
    public Goods buildGoods(SpuBo spuBo) {
        Goods goods = new Goods();


        //相同属性赋值
        BeanUtils.copyProperties(spuBo, goods);

        //四个值无法赋值，需要手动加值

        List<String> names = this.categoryClient.queryNameByIds(Arrays.asList(spuBo.getCid1(), spuBo.getCid2(), spuBo.getCid3()));

        String all = spuBo.getTitle() + " " + StringUtils.join(names, " ");


        goods.setAll(all);


        //根据spuid查询当前所有的sku

        List<Sku> skus = this.goodsClient.querySkuBySpuId(spuBo.getId());
        //存sku的价格
        List<Long> prices = new ArrayList<>();

        //存储sku
        List<Map<String, Object>> skuList = new ArrayList<>();

        skus.forEach(sku -> {
            //获取所有的价格
            prices.add(sku.getPrice());
            Map<String, Object> skuMap = new HashMap<>();
            skuMap.put("id", sku.getId());
            skuMap.put("title", sku.getTitle());
            skuMap.put("image", StringUtils.isBlank(sku.getImages()) ? "" : sku.getImages().split(",")[0]);
            skuMap.put("price", sku.getPrice());
            skuList.add(skuMap);
        });

        //spuDetail
        SpuDetail spuDetail = this.goodsClient.querySpuDetailById(spuBo.getId());

        //查询分类对应的规格参数
        List<SpecParam> params = this.specificationClient.querySpecParam(null, spuBo.getCid3(), true);

        //通用规格参数的值
        Map<Long, String> genericMap = JsonUtils.parseMap(spuDetail.getGenericSpec(), Long.class, String.class);

        //特有规格参数的值
        Map<Long, List<String>> specialMap = JsonUtils.nativeRead(spuDetail.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });

        //处理规格参数显示问题，默认显示id+值，处理后显示id对应的名称+值

        Map<String, Object> specs = new HashMap<>();

        params.forEach(param -> {

            Long paramId = param.getId();
            String name = param.getName();
            //通用参数
            Object value = null;
            if (param.getGeneric()) {
                //通用参数
                value = genericMap.get(paramId);


                if (param.getNumeric()) {
                    //数值类型需要加分段
                    value = this.chooseSegment(value.toString(), param);
                }

//                if (param.getNumeric()) {
//                    //数值类型需要加分段
//                    if (param.getSegments() != null && !"".equals(param.getSegments())) {
//                        value = this.chooseSegment(value.toString(), param);
//                    }
//                }
            } else {
                //特有参数
                value = specialMap.get(paramId);
            }
            if (null == value) {
                value = "其他";
            }
            specs.put(name, value);
        });


        goods.setSkus(JsonUtils.serialize(skuList));

        goods.setPrice(prices);

        goods.setSpecs(specs);
        return goods;
    }

    private String chooseSegment(String value, SpecParam p) {
        double val = NumberUtils.toDouble(value);
        String result = "其它";

        //保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");

            //获取数值范围
            double begin = NumberUtils.toDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = NumberUtils.toDouble(segs[1]);
            }

            //判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

}
